﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using FlashPay.Entity;
using FlashPay.Service.Interface;
using FlashPay.Entity.Parameter;
using FlashPay.Util;
using FlashPay.Entity.Request.User;
using System.Text.RegularExpressions;
using FlashPay.Entity.Response.User;
using FlashPay.DAO.Interface;
using FlashPay.Entity.Response.Company;
using Microsoft.AspNetCore.Http;

namespace FlashPay.Admin.Controllers
{
    /// <summary>
    /// 用户控制器
    /// </summary>
    public class UserController : BaseController
    {
        /// <summary>
        /// 用户业务接口
        /// </summary>
        private readonly UserInfoService _userService;

        /// <summary>
        /// 公司数据接口
        /// </summary>
        private readonly CompanyDao _companyDao;

        /// <summary>
        /// 缓存
        /// </summary>
        private readonly MemoryCacheUtil _memoryCacheUtil;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="_manage"></param>
        /// <param name="userService">用户业务接口</param>
        /// <param name="memoryCacheUtil">缓存</param>
        public UserController(IAuthenticate<TicketResponse> _manage, IHttpContextAccessor _accessor, UserInfoService userService, CompanyDao companyDao, MemoryCacheUtil memoryCacheUtil) : base(_manage, _accessor)
        {
            _memoryCacheUtil = memoryCacheUtil;
            _userService = userService;
            _companyDao = companyDao;
        }

        /// <summary>
        /// 获取用户
        /// </summary>
        /// <param name="id">用户编号</param>
        /// <returns></returns>
        public JsonResult GetUser(int? id)
        {
            var userInfo = _userService.GetById(_manage.data, id);

            return Json(userInfo);
        }

        /// <summary>
        /// 根据编号获取公司
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns>Company</returns>
        private List<CompanyResponse> GetCompany(int companyId, int level)
        {
            var companyRequest = new EF.Models.Company()
            {
                CompanyId = companyId,
                CompanyPid = -1,
                CompanyStatus = 1
            };

            var companyList = new BaseModel<List<EF.Models.Company>>();

            _companyDao.Get(companyList, companyRequest, level);
            var companyResponse = new List<CompanyResponse>();
            if (companyList.Success)
            {
                foreach (var item in companyList.Result)
                {
                    companyResponse.Add(new CompanyResponse()
                    {
                        CompanyID = item.CompanyId,
                        CompanyName = item.CompanyName,
                        CompanyStatus = item.CompanyStatus
                    });
                }
            }
            return companyResponse;
        }

        /// <summary>
        /// 新增、编辑
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        [AuthorizeFilter(AuthCode.User0002, AuthCode.User0003)]
        public JsonResult SaveOrEditUserInfo(SaveOrEditUserInfoRequest userInfo,List<int> roleIds)
        {
            //输出
            var response = new JResult()
            {
                Success = false
            };

            if (userInfo.Id > 0)
            {

            }
            else {

                if (string.IsNullOrEmpty(userInfo.LoginName)) {
                    response.ErrorMessage = "登陆名称不能为空";
                    return Json(response);
                }
                userInfo.LoginName = Regex.Replace(userInfo.LoginName.Trim(), @"\s", "");

                Regex reg = new Regex(@"^[\u4E00-\u9FA5A-Za-z0-9_]+$");
                if (!reg.IsMatch(userInfo.LoginName))
                {
                    response.ErrorMessage = "登陆名称由中文、英文、数字包括下划线";
                    return Json(response);
                }

                if (userInfo.NewPassWord != userInfo.ConfirmNewPassWord)
                {
                    response.ErrorMessage = "两次输入的密码不一致";
                    return Json(response);
                }
            }

            #region 验证
            //电话号码
            if (!string.IsNullOrEmpty(userInfo.Telephone))
            {
                Regex reg = new Regex(@"^[0-9]*$");
                if (!reg.IsMatch(userInfo.Telephone))
                {
                    response.ErrorMessage = "电话号码只能输入数字";
                    return Json(response);
                }
                userInfo.Telephone = Regex.Replace(userInfo.Telephone.Trim(), @"\s", "");
            }

            //邮箱
            if (!string.IsNullOrEmpty(userInfo.Email))
            {
                Regex reg = new Regex(@"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$");
                if (!reg.IsMatch(userInfo.Email))
                {
                    response.ErrorMessage = "邮箱格式有误";
                    return Json(response);
                }

                userInfo.Email = Regex.Replace(userInfo.Email.Trim(), @"\s", "");
            }

            //说明
            if (!string.IsNullOrEmpty(userInfo.Description))
            {
                Regex reg = new Regex(@"^[\u4E00-\u9FA5A-Za-z0-9_]+$");
                if (!reg.IsMatch(userInfo.Description))
                {
                    response.ErrorMessage = "说明由中文、英文、数字包括下划线";
                    return Json(response);
                }

                userInfo.Description = Regex.Replace(userInfo.Description.Trim(), @"\s", "");
            }
            #endregion

            userInfo.LoginUserCompanyId = _manage.data.CompanyID;
            userInfo.UCreateId = _manage.data.UserID;
            userInfo.LoginUserId = _manage.data.UserID;
            userInfo.RoleIds = roleIds;
            userInfo.UserName = _manage.data.UserName;
            response = _userService.SaveOrEditUserInfo(userInfo, roleIds);

            return Json(response);
        }



        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取当前登陆用户信息
        /// </summary>
        /// <returns></returns>
        public JsonResult GetUserInfo()
        {
            var token = HttpContext.Request.Headers["token"];

            var ticketResponse = new TicketResponse();

            if (!string.IsNullOrEmpty(token))
            {
                ticketResponse = _manage.Get(token);
            }

            var response = _userService.Get(ticketResponse.UserID);

            return Json(response);

        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>PagedList</returns>
        [AuthorizeFilter(AuthCode.User0001)]
        public JsonResult GetPager(UserInfoQuery query)
        {
            if (query != null)
            {
                return GetCommon(query);
            }
            else
            {
                return Json(new JResult { Success = false, ErrorMessage = "未获取到数据" });
            }
        }

        //公共Get方法
        public JsonResult GetCommon(UserInfoQuery query)
        {
            query.Id = _manage.data.UserID;
            query.CompanyId = _manage.data.CompanyID;
            query.UCreateId = _manage.data.UserID;
            //获取分页列表
            var pager = _userService.GetPager(query);

            if (pager.Success)
            {
                bool ResetPassWord = false;
                List<string> userPermission = _manage.data.UserPermission;
                if (userPermission != null && userPermission.Count > 0)
                {
                    ResetPassWord = userPermission.Where(e => e.Contains("User0012")).FirstOrDefault() != null;
                }

                for (int i = 0; i < pager.TData.Count; i++)
                {
                    //用于判断当前登陆用户的操作权限
                    pager.TData[i].UUiconfig = _manage.data.UserID.ToString();
                    if (ResetPassWord)
                    {
                        pager.StatusCode = "1";//是否有重置密码的权限
                    }
                }
            }
            return Json(pager);
        }

        //查看详情
        [AuthorizeFilter(AuthCode.User0003, AuthCode.AllowEdit)]
        public JsonResult GetDetail(UserInfoQuery query)
        {
            if (query != null)
            {
                return GetCommon(query);
            }
            else
            {
                return Json(new JResult { Success = false, ErrorMessage = "未获取到数据" });
            }
        }

        //删除用户
        [AuthorizeFilter(AuthCode.User0006)]
        public JsonResult Delete(UserInfoQuery query)
        {
            var returnInfo = _userService.Delete(query);
            return Json(returnInfo);
        }

        //修改状态
        [AuthorizeFilter(AuthCode.User0004)]
        public JsonResult ChangeStatus(UserInfoQuery query)
        {
            var returnInfo = _userService.UpdateStatus(query);
            return Json(returnInfo);
        }

        //修改谷歌验证状态
        [AuthorizeFilter(AuthCode.User0007)]
        public JsonResult ChangeLoggedIn(EF.Models.UserInfo query)
        {
            var returnInfo = _userService.ChangeLoggedIn(query);
            return Json(returnInfo);
        }

        /// <summary>
        /// 下拉列表查询
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>List</returns>
        public JsonResult GetSelectList(UserInfoQuery query)
        {
            query.CompanyId = _manage.data.CompanyID;
            var list = _userService.GetList(query);
            return Json(list);
        }

        //保存用户
        [AuthorizeFilter(AuthCode.User0002, AuthCode.User0003)]
        public JsonResult SaveUserInfo([FromBody] UserInfoQuery query)
        {
            if (!ModelState.IsValid)
            {
                var message = ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage).FirstOrDefault();
                return Json(new JResult { ErrorMessage = message, Success = false });
            }
            var list = _userService.SaveUserInfo(query);
            return Json(list);
        }



        /// <summary>
        /// 通过条件获取用户信息
        /// </summary>
        public JsonResult SearchUserInfo(string SearchValue)
        {
            int CompanyId = _manage.data.CompanyID;
            var result = _userService.SearchUserInfo(SearchValue, CompanyId);
            return Json(result);
        }
    }
}